package org.layuiframework.generator.util;

import java.io.*;

public class FileUtil {

    /**
     * @method 将字符串保存到指定的文件中
     * @param filePath  文件路径
     * @param content   保存内容
     * @throws IOException
     */
    public static void writeString(String filePath, String content) throws IOException {
        BufferedWriter writer = null;
        File file = new File(filePath);
        if(!file.exists()) file.createNewFile();
        try {
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file,false), "UTF-8"));
            writer.write(content);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(writer != null) writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @method 从指定的文件中读取出文件里面的字符串
     * @param filePath  文件路径
     * @return  文件内容字符串
     */
    public static String readString(String filePath) {
        BufferedReader reader = null;
        StringBuilder lastStr = new StringBuilder();
        try {
            FileInputStream fileInputStream = new FileInputStream(filePath);
            InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
            reader = new BufferedReader(inputStreamReader);
            String tempString = null;
            while ((tempString = reader.readLine()) != null) {
                lastStr.append(tempString);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(reader != null) reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return lastStr.toString();
    }
}
